package com.lins.store.config.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/** 定义处理器拦截器 */
public class LoginInterceptor implements HandlerInterceptor {

    //注入方式不行
//    @Autowired
//    UserMapper userMapper;

    /**
     * spring mvc的拦截器
     * 目的：检测session中是否有uid，验证是否登录
     * @param request
     * @param response
     * @param handler 处理器(url+controller 映射)
     * @return true:放行  false：返回登录页
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Integer uid = (Integer) session.getAttribute("uid");

        String queryUrl = request.getQueryString() == null ? "" : ("?" + request.getQueryString());
        String requestUrl = request.getServletPath() + queryUrl;

        //用户没有登录
        if (uid == null) {
            //有效链接才会保存原url
            if (requestUrl.length() >= 5){
                if ("/web/".equals(requestUrl.substring(0, 5))){
                    session.setAttribute("oldURL", requestUrl);
                }
            }
            response.sendRedirect("/web/login.html");
            return false;
        }

        //认证-权限-角色，此处是权限：若普通用户访问管理员页面,强制回到普通首页
        if (requestUrl.length() >= 20){
            if ("/web/adminIndex.html".equals(requestUrl.substring(0,20))){
                if (uid != 1 && uid != 11){
                    response.sendRedirect("/web/index.html");
                    return false;
                }
            }
        }
        return true;
    }

    //
}
